<template>
  <je-panel v-bind="lauoutOptions" class="query-advanced">
    <template #top>
      <!-- <div class="remark">
        <span>
          备注：高级查询会展示在列表的上方，当字段设置为非常用查询的时候默认将会被收起。
        </span>
      </div> -->
      <je-form
        :model="formState"
        style="display: flex; padding: 10px 20px"
        autocomplete="off"
        :colon="false"
      >
        <je-form-item label="布局配置方式" name="layout">
          <je-select
            v-model:value="formState.layout"
            :options="layoutModes"
            :allow-clear="false"
          ></je-select>
        </je-form-item>
        <je-form-item
          v-if="formState.layout == 'gridLayout'"
          name="column"
          label="栅格布局列数"
          style="margin-left: 30px"
        >
          <je-select v-model:value="formState.column" :options="columnData"></je-select>
        </je-form-item>
        <je-form-item
          v-if="formState.layout == 'gridLayout'"
          label="标题宽"
          style="margin-left: 30px"
          name="labelWidth"
        >
          <je-input-number v-model:value="formState.labelWidth" :min="0" />
        </je-form-item>
        <je-form-item
          label="高级查询禁用change事件"
          style="margin-left: 30px"
          name="disabledChange"
        >
          <je-switch v-model:value="formState.disabledChange" mode="checkbox"></je-switch>
        </je-form-item>
        <je-form-item label="启用搜索按钮" style="margin-left: 30px" name="openButton">
          <je-switch v-model:value="formState.openButton" mode="checkbox"></je-switch>
        </je-form-item>
        <je-form-item label="启用导出按钮" style="margin-left: 30px" name="startExportBtn">
          <je-switch v-model:value="formState.startExportBtn" mode="checkbox"></je-switch>
        </je-form-item>
        <TbFill />

        <!-- <je-form-item style="margin-left: 30px" name="enable">
          <template #label>
            是否启用存为查询策略
            <i class="fas fa-flower" style="color: rgb(235, 235, 235)"></i>
          </template>
          <je-switch v-model:value="formState.enable" mode="checkbox"></je-switch>
        </je-form-item> -->
      </je-form>
    </template>
    <template #default>
      <je-table
        ref="xTable"
        border
        class="query-advanced-table"
        stripe
        size="mini"
        auto-resize
        draggable
        show-overflow
        keep-source
        show-header-overflow
        :store="tableData"
        resizable
        :edit-config="{
          trigger: 'click',
          mode: 'cell',
          showUpdateStatus: true,
          activeMethod: isTableEdit,
        }"
        :row-config="{ isCurrent: true, isHover: true }"
        :loading="loading"
        header-align="center"
        :row-style="rowStyle"
        id-property="JE_CORE_GROUPQUERY_ID"
        @drop="sortTable"
      >
        <je-column type="checkbox" width="40" align="center"></je-column>
        <je-column field="SY_ORDERINDEX" title="序号" width="60" align="center" :edit-render="{}">
          <template #edit="{ row }">
            {{ row.SY_ORDERINDEX }}
          </template>
        </je-column>
        <je-column field="GROUPQUERY_MC" title="字段名称" :edit-render="inputRender" width="180">
          <template #edit="{ row }">
            <je-input v-model:value="row.GROUPQUERY_MC" />
          </template>
        </je-column>
        <je-column field="GROUPQUERY_BM" title="字段编码" width="180"> </je-column>
        <je-column
          field="GROUPQUERY_SHOW_QUERY_TYPE"
          title="展示查询类型"
          width="120"
          align="center"
        >
          <template #default="{ row }">
            <je-switch
              v-if="row.GROUPQUERY_BM != '-'"
              v-model:value="row.GROUPQUERY_SHOW_QUERY_TYPE"
              mode="checkbox"
              :empty-value="true"
            />
          </template>
          <template #edit="{ row }">
            <je-switch
              v-model:value="row.GROUPQUERY_SHOW_QUERY_TYPE"
              mode="checkbox"
              :empty-value="true"
            />
          </template>
        </je-column>
        <je-column
          field="GROUPQUERY_CXLX"
          title="查询类型"
          width="100"
          :edit-render="{}"
          align="center"
        >
          <template #edit="{ row }">
            <je-select v-model:value="row.GROUPQUERY_CXLX">
              <je-select-option
                v-for="item in row.QUERYADVANCED_OPTIONS"
                :key="item.value"
                :value="item.value"
              >
                {{ item.label }}
              </je-select-option>
            </je-select>
          </template>
          <template #default="{ row }">
            {{ getSelectLabel(row.GROUPQUERY_CXLX, row.QUERYADVANCED_OPTIONS) }}
          </template>
        </je-column>

        <!-- <je-column
          field="GROUPQUERY_FIELD_TYPE"
          title="字段类型"
          width="100"
          align="center"
          :edit-render="{}"
        >
          <template #default="{ row }">
            {{ getSelectTypeLabel(row.GROUPQUERY_FIELD_TYPE, RESOURCEFIELD_XTYPE) }}
          </template>
          <template #edit="{ row }">
            <je-select
              v-model:value="row.GROUPQUERY_FIELD_TYPE"
              :options="row.FIELDDATA"
              @change="changeFieldType(row)"
            ></je-select>
          </template>
        </je-column> -->
        <je-column field="GROUPQUERY_BQYC" title="标签隐藏" width="100" align="center">
          <template #default="{ row }">
            <je-switch
              v-if="row.GROUPQUERY_BM != '-'"
              v-model:value="row.GROUPQUERY_BQYC"
              mode="checkbox"
            />
          </template>
          <template #edit="{ row }">
            <je-switch v-model:value="row.GROUPQUERY_BQYC" mode="checkbox" />
          </template>
        </je-column>

        <je-column field="GROUPQUERY_ALLOW_SORT" title="允许排序" width="100" align="center">
          <template #default="{ row }">
            <je-switch
              v-if="row.GROUPQUERY_BM != '-'"
              v-model:value="row.GROUPQUERY_ALLOW_SORT"
              mode="checkbox"
            />
          </template>
          <template #edit="{ row }">
            <je-switch v-model:value="row.GROUPQUERY_ALLOW_SORT" mode="checkbox" />
          </template>
        </je-column>
        <!-- <je-column field="GROUPQUERY_CHOICEANDEDIT" title="可选可编辑" width="100" align="center">
          <template #default="{ row }">
            <je-switch
              v-if="row.GROUPQUERY_BM != '-'"
              v-model:value="row.GROUPQUERY_CHOICEANDEDIT"
              mode="checkbox"
            />
          </template>
          <template #edit="{ row }">
            <je-switch v-model:value="row.GROUPQUERY_CHOICEANDEDIT" mode="checkbox" />
          </template>
        </je-column> -->
        <je-column
          v-if="formState.layout == 'gridLayout'"
          field="GROUPQUERY_SZLS"
          title="列"
          align="center"
          :edit-render="{}"
        >
          <template #default="{ row }">
            {{ getSelectLabel(row.GROUPQUERY_SZLS, columnData) }}
          </template>
          <template #edit="{ row }">
            <je-select v-model:value="row.GROUPQUERY_SZLS" :options="columnData"></je-select>
          </template>
        </je-column>
        <je-column
          v-if="formState.layout == 'flowLayout'"
          field="GROUPQUERY_BQKD"
          title="标签宽度"
          width="80"
          :edit-render="numberRender"
          align="center"
        >
          <template #edit="{ row }">
            <je-input-number v-model:value="row.GROUPQUERY_BQKD" :min="0" />
          </template>
        </je-column>
        <je-column
          v-if="formState.layout == 'flowLayout'"
          field="GROUPQUERY_KD"
          title="总宽度"
          min-width="66"
          align="center"
          :edit-render="numberRender"
        >
          <template #edit="{ row }">
            <je-input-number v-model:value="row.GROUPQUERY_KD" :min="0" />
          </template>
        </je-column>

        <template #tbar>
          <div class="tabletop-button">
            <div>
              <je-button type="text" @click="addData(false)">
                <template #icon><i class="fal fa-file-import"></i></template>
                导入
              </je-button>
              <je-button type="text" @click="addData(true)">
                <template #icon><i class="fal fa-plus-circle"></i></template>
                添加换行符
              </je-button>
              <je-button type="text" @click="doDelete">
                <template #icon><i class="fal fa-times"></i></template>
                删除
              </je-button>
            </div>
            <div style="padding: 4px 0">
              <je-input-search
                v-model:value.tirm="searchValue"
                placeholder="搜索"
                style="width: 280px"
                :allow-clear="allowclear"
                enter-button="搜索"
              >
                <template #prefix> <i class="fal fa-search" /> </template>
              </je-input-search>
            </div>
          </div>
        </template>
      </je-table>
    </template>
    <template #bottom>
      <div style="line-height: 60px; text-align: center">
        <je-button type="primary" style="margin-right: 5px" @click="doSaveData('')">确定</je-button>
        <je-button style="margin-left: 5px" @click="onClose">取消</je-button>
      </div>
    </template>
  </je-panel>
</template>

<script>
  import { defineComponent, ref, reactive, onMounted, watch, toRefs } from 'vue';
  import {
    Input,
    Modal,
    Button,
    Grid,
    InputNumber,
    Panel,
    Select,
    Toolbar,
    Switch,
    Data,
  } from '@jecloud/ui';
  import { queryAdvancedGetData, queryAdvancedSave, doRemove } from '@/api/index';
  import { inputRender, numberRender } from '@/helper/edit-render';
  import { QUERYADVANCED_OPTIONS_TYPE } from './constant';
  import { SelectWindow } from '@jecloud/func';

  export default defineComponent({
    name: 'QueryAdvanced',
    components: {
      JeInput: Input,
      JeButton: Button,
      JeTable: Grid,
      JeColumn: Grid.Column,
      JeInputNumber: InputNumber,
      JePanel: Panel,
      TbFill: Toolbar.Fill, // 填充元素
      JeInputSearch: Input.Search,
      JeSelect: Select,
      JeSelectOption: Select.Option,
      JeSwitch: Switch,
    },
    props: {
      recordData: {
        type: Object,
        default: () => {
          return {};
        },
      },
    },
    emits: ['btnClick'],
    setup(props, { emit }) {
      const state = reactive({
        xTable: ref(),
        tableData: Data.Store.useGridStore({
          data: [],
        }),
        loading: true,
        addShow: false,
        searchValue: '',
        layoutModes: [
          { value: 'flowLayout', label: '流式布局' },
          { value: 'gridLayout', label: '栅格布局' },
        ], // 布局方式的数据
        formState: {
          layout: 'flowLayout',
          enable: '0',
          column: '3',
          labelWidth: '140',
          disabledChange: '',
          openButton: '',
          startExportBtn: '0',
        }, //表单里面的数据
        columnData: [
          { value: '1', label: 1 },
          { value: '2', label: 2 },
          { value: '3', label: 3 },
          { value: '4', label: 4 },
          { value: '6', label: 6 },
        ],
        QUERYADVANCED_OPTIONS_TYPE,
        ModalObj: Modal.useInjectModal(),
      });
      watch(
        () => state.searchValue,
        () => {
          getTableData();
        },
        { deep: true },
      );
      onMounted(() => {
        getTableData();
      });
      //列表单元格格式化
      const getSelectLabel = (value, list, valueProp = 'value', labelField = 'label') => {
        if (!value) return '';
        const item = list.find((item) => item[valueProp] === value);
        return item ? item[labelField] : null;
      };
      //初始化列表数据
      const getTableData = () => {
        queryAdvancedGetData({
          funcId: props.recordData.id,
          queryStr: state.searchValue,
          sort: 'ORDER BY SY_ORDERINDEX ASC',
        })
          .then((data) => {
            data.rows.forEach((item) => {
              delete item.SY_CREATEORGNAME;
              delete item.SY_CREATETIME;
              delete item.SY_CREATEUSERID;
              delete item.SY_CREATEUSERNAME;
              delete item.SY_STATUS;
              item.GROUPQUERY_SZLS = item.GROUPQUERY_SZLS || 1;
              const typeData = QUERYADVANCED_OPTIONS_TYPE[item.GROUPQUERY_FIELD_TYPE] || [
                { value: 'like', label: '模糊' },
              ];
              item.QUERYADVANCED_OPTIONS = typeData;
            });
            state.formState.layout = data.FUNCINFO_LAYOUT_TYPE || 'flowLayout';
            state.formState.enable = data.FUNCINFO_ADD_QUERY_STRATEGY || '0';
            state.formState.column = data.FUNCINFO_LAYOUT_COLUMN_COUNT || '3';
            state.formState.labelWidth = data.FUNCINFO_GROUPQUERY_LABEL_WIDTH || '140';
            state.formState.disabledChange = data.FUNCINFO_DISABLE_CHANGE || '0';
            state.formState.openButton = data.FUNCINFO_GROUPQUERY_ENABEL_QUERY || '0';
            state.formState.startExportBtn = data.FUNCINFO_GROUPQUERY_START_EXPORT || '0';
            state.tableData.loadData(data.rows);
            state.loading = false;
          })
          .catch((e) => {
            Modal.alert(e.message, 'error');
          });
      };

      //关闭弹窗
      const cancelModal = () => {
        emit('btnClick');
      };
      //添加数据
      const addData = (type) => {
        if (state.searchValue) {
          Modal.alert('请先清空搜索框里的值！', 'info');
          return false;
        }
        //添加换行符
        let strData = [];
        if (type) {
          const strData = [
            {
              GROUPQUERY_MC: '换行符',
              GROUPQUERY_BM: '-',
              GROUPQUERY_GNID: props.recordData.id,
              SY_ORDERINDEX: state.tableData.data.length + 1,
            },
          ];
          state.tableData.insert(strData, -1);
          doSaveInster(
            {
              strData: JSON.stringify(strData),
              tableCode: 'JE_CORE_GROUPQUERY',
              funcId: props.recordData.id,
              FUNCINFO_LAYOUT_TYPE: state.formState.layout,
              FUNCINFO_ADD_QUERY_STRATEGY: state.formState.enable,
              FUNCINFO_LAYOUT_COLUMN_COUNT: state.formState.column,
              FUNCINFO_GROUPQUERY_LABEL_WIDTH: state.formState.labelWidth,
              FUNCINFO_DISABLE_CHANGE: state.formState.disabledChange,
              FUNCINFO_GROUPQUERY_ENABEL_QUERY: state.formState.openButton,
              FUNCINFO_GROUPQUERY_START_EXPORT: state.formState.startExportBtn,
            },
            true,
          );
        } else {
          const code = [];
          state.tableData.data.forEach((item) => {
            code.push(item.GROUPQUERY_BM);
          });
          SelectWindow.show({
            title: '导入',
            type: 'grid',
            orders: [{ code: 'SY_ORDERINDEX', type: 'ASC' }],
            querys: [
              {
                code: 'RESOURCECOLUMN_FUNCINFO_ID',
                value: props.recordData.id,
                type: '=',
                cn: 'and',
              },
              {
                code: 'RESOURCECOLUMN_XTYPE',
                value: 'uxcolumn',
                type: '=',
                cn: 'and',
              },
              {
                code: 'RESOURCECOLUMN_CODE',
                value: code,
                type: 'notIn',
                cn: 'and',
              },
            ],
            configInfo: 'JE_CORE_COLUMNFIELD_VIEW,,,M',
            callback: function ({ rows }) {
              if (rows && rows.length) {
                rows.forEach((item) => {
                  const typeData = QUERYADVANCED_OPTIONS_TYPE[item.RESOURCEFIELD_XTYPE] || [
                    { value: 'like', label: '模糊' },
                  ];
                  const obj = {
                    GROUPQUERY_MC: item.RESOURCECOLUMN_NAME,
                    GROUPQUERY_BM: item.RESOURCECOLUMN_CODE,
                    GROUPQUERY_GNID: props.recordData.id,
                    QUERYADVANCED_OPTIONS: typeData,
                    GROUPQUERY_CXLX: typeData[0].value,
                    GROUPQUERY_BQKD: '140',
                    GROUPQUERY_KD: '350',
                    GROUPQUERY_BQYC: '0',
                    GROUPQUERY_FIELD_TYPE: item.RESOURCEFIELD_XTYPE,
                    GROUPQUERY_ALLOW_SORT: '0',
                    GROUPQUERY_SHOW_QUERY_TYPE: '0',
                    GROUPQUERY_CHOICEANDEDIT: '0',
                    GROUPQUERY_SZLS: 1,
                    SY_ORDERINDEX: state.tableData.data.length + 1,
                  };
                  state.tableData.insert(obj, -1);
                  strData.push(obj);
                });

                doSaveInster(
                  {
                    strData: JSON.stringify(strData),
                    tableCode: 'JE_CORE_GROUPQUERY',
                    funcId: props.recordData.id,
                    FUNCINFO_LAYOUT_TYPE: state.formState.layout,
                    FUNCINFO_ADD_QUERY_STRATEGY: state.formState.enable,
                    FUNCINFO_LAYOUT_COLUMN_COUNT: state.formState.column,
                    FUNCINFO_GROUPQUERY_LABEL_WIDTH: state.formState.labelWidth,
                    FUNCINFO_DISABLE_CHANGE: state.formState.disabledChange,
                    FUNCINFO_GROUPQUERY_ENABEL_QUERY: state.formState.openButton,
                    FUNCINFO_GROUPQUERY_START_EXPORT: state.formState.startExportBtn,
                  },
                  true,
                );
              }
            },
          });
        }
      };

      //删除
      const doDelete = () => {
        const checkboxRecords = state.xTable.getCheckboxRecords();
        if (checkboxRecords.length <= 0) {
          return Modal.alert('请选择要删除的数据！', 'warning');
        }
        Modal.confirm('是否删除数据?', () => {
          const ids = [];
          checkboxRecords.forEach((record) => {
            ids.push(record.JE_CORE_GROUPQUERY_ID);
          });
          doRemove({
            ids: ids.join(','),
            tableCode: 'JE_CORE_GROUPQUERY',
          })
            .then((data) => {
              checkboxRecords.forEach((item) => {
                state.tableData.remove(item);
              });
              Modal.message(data.message, 'success');
            })
            .catch((e) => {
              Modal.alert(e.message, 'error');
            });
        });
      };
      //保存
      const doSaveData = (flag) => {
        const updateRecords = state.tableData.data || [];
        updateRecords.forEach((item) => {
          delete item.__action__;
        });
        doSaveInster(
          {
            strData: JSON.stringify(updateRecords),
            tableCode: 'JE_CORE_GROUPQUERY',
            funcId: props.recordData.id,
            FUNCINFO_LAYOUT_TYPE: state.formState.layout,
            FUNCINFO_ADD_QUERY_STRATEGY: state.formState.enable,
            FUNCINFO_LAYOUT_COLUMN_COUNT: state.formState.column,
            FUNCINFO_GROUPQUERY_LABEL_WIDTH: state.formState.labelWidth,
            FUNCINFO_DISABLE_CHANGE: state.formState.disabledChange,
            FUNCINFO_GROUPQUERY_ENABEL_QUERY: state.formState.openButton,
            FUNCINFO_GROUPQUERY_START_EXPORT: state.formState.startExportBtn,
          },
          flag,
        );
      };
      //拖拽
      const sortTable = () => {
        state.tableData.data.forEach((item, index) => {
          item.SY_ORDERINDEX = index + 1;
        });
      };
      const doSaveInster = (params, flag) => {
        const data = (params.strData && JSON.parse(params.strData)) || [];
        data.forEach((item) => {
          delete item.QUERYADVANCED_OPTIONS;
          delete item.FIELDDATA;
        });
        params.strData = JSON.stringify(data);
        queryAdvancedSave(params)
          .then((data) => {
            if (flag) {
              getTableData();
            } else {
              Modal.message(data.message, 'success');
              state.ModalObj.close();
            }
          })
          .catch((e) => {
            Modal.alert(e.message, 'error');
          });
      };

      const getSelectTypeLabel = (value, list, valueProp = 'code', labelField = 'text') => {
        if (!value) return '';
        const item = list.find((item) => item[valueProp] === value);
        return item ? item[labelField] : null;
      };
      const rowStyle = ({ row }) => {
        if (row.GROUPQUERY_BM == '-') {
          return {
            backgroundColor: '#f5f5f5',
          };
        }
      };
      const isTableEdit = ({ row, column }) => {
        if (
          row.GROUPQUERY_BM == '-' &&
          [
            'GROUPQUERY_SHOW_QUERY_TYPE',
            'GROUPQUERY_CXLX',
            'GROUPQUERY_SZLS',
            'GROUPQUERY_BQKD',
            'GROUPQUERY_KD',
            'GROUPQUERY_BQYC',
            'GROUPQUERY_FIELD_TYPE',
            'GROUPQUERY_ALLOW_SORT',
            'GROUPQUERY_ZSCXLX',
            'GROUPQUERY_CHOICEANDEDIT',
          ].includes(column.field)
        ) {
          return false;
        }
        return true;
      };
      const onClose = () => {
        state.ModalObj.close();
      };
      const changeFieldType = (row) => {
        if (row.GROUPQUERY_FIELD_TYPE == 'textfield') {
          const typeData = QUERYADVANCED_OPTIONS_TYPE[row.GROUPQUERY_FIELD_TYPE];
          row.QUERYADVANCED_OPTIONS = typeData;
          row.GROUPQUERY_CXLX = typeData[0].value;
        }
      };
      return {
        changeFieldType,
        isTableEdit,
        onClose,
        ...toRefs(state),
        cancelModal,
        inputRender,
        numberRender,
        addData,
        doDelete,
        doSaveData,
        getSelectLabel,
        lauoutOptions: { top: { size: 50, class: 'advaned-title' }, bottom: { size: 60 } },
        allowclear: true,
        getTableData,
        sortTable,
        rowStyle,
        getSelectTypeLabel,
      };
    },
  });
</script>

<style lang="less" scoped>
  .query-advanced {
    .advaned-title {
      .remark {
        height: 40px;
        width: 100%;
        background: #faf9da;
        border: 1px solid #b8741a;
        padding: 0 15px;
        margin-bottom: 10px;
        span {
          color: #b8741a;
          font-size: 14px;
          line-height: 40px;
        }
      }
    }
    .query-advanced-table {
      .tabletop-button {
        height: 40px;
        border-top: 1px solid #e6e6e6;
        border-left: 1px solid #e6e6e6;
        border-right: 1px solid #e6e6e6;
        display: flex;
        border-top: 1px solid #e6e6e6;
        justify-content: space-between;
        height: 40px;
        line-height: 39px;
        padding-right: 16px;
        padding-left: 4px;
        .ant-input-search {
          border-bottom-right-radius: 0;
          border-top-right-radius: 0;
        }
        .ant-input-search.ant-input-affix-wrapper:hover {
          border: 1px solid #5c8dff !important;
          box-shadow: none !important;
        }
        .ant-input-search.ant-input-affix-wrapper-focused {
          border: 1px solid #5c8dff !important;
          box-shadow: none !important;
        }
        .ant-input-search-button {
          width: 60px;
        }
      }
    }
  }
</style>
<style lang="less">
  .query-advanced {
    .query-advanced-table {
      .ant-input-search {
        border-bottom-right-radius: 0;
        border-top-right-radius: 0;
      }
      .ant-input-search.ant-input-affix-wrapper:hover {
        border: 1px solid #5c8dff !important;
        box-shadow: none !important;
      }
      .ant-input-search.ant-input-affix-wrapper-focused {
        border: 1px solid #5c8dff !important;
        box-shadow: none !important;
      }
      .ant-input-search-button {
        width: 60px;
      }
    }
  }
</style>
